import { Helmet } from 'react-helmet';
import { Link, router } from 'umi';
import React, { Children, useEffect, useState, useMemo } from 'react';
import { HomeOutlined } from '@ant-design/icons';
import { Layout, Menu, Breadcrumb, Result, Button } from 'antd';
import { Dispatch } from 'redux';
import { RouteChildrenProps } from 'react-router';
import { connect } from 'dva';
import { ClickParam } from 'antd/es/menu';
import { ConnectProps, ConnectState } from '@/models/connect';
import CommonFooter from '@/components/CommonFooter';
import Avatar from '@/components/GlobalHeader/AvatarDropdown';
import { BasicLayoutProps as ProLayoutProps } from '@ant-design/pro-layout';
import { roles } from '@/constants/index';
import Authorized from '@/utils/Authorized';
import { getAuthorityFromRouter, getPageQuery } from '@/utils/utils';
import styles from './PlatformLayout.less';
import logo from '../assets/logo.svg';
import defaultSetting from '../../config/defaultSettings';
import { CurrentUser } from '../models/user';

const { Header, Content, Footer } = Layout;

const menuList = [
  { path: '/', label: '首页', role: [roles.admin, roles.user] },
  { path: '/userList', label: '用户管理', role: [roles.admin, roles.user] },
];

const noMatch = (
  <Result
    status="403"
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={<Button type="primary">重新登录</Button>}
  />
);

interface PlatformLayoutProps extends RouteChildrenProps {
  dispatch: Dispatch<any>;
  currentUser?: Partial<CurrentUser>;
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
}

const PlatformLayout: React.FC<PlatformLayoutProps> = props => {
  const onMenuClick = (event: ClickParam) => {
    const { key } = event;

    router.push(key);
  };

  const selectKey = useMemo(() => {
    // @ts-ignore
    let rootPath = props.location.pathname.match(/(\/[^/]*)/gi)[0];
    if (rootPath.startsWith('/student') && rootPath !== '/studentList') {
      rootPath = '/studentList';
    }
    return rootPath;
  }, [props.location.pathname]);

  const userCenterPath = useMemo(() => {
    let studentId = '';
    // @ts-ignore
    const rootPath = props.location.pathname.match(/(\/[^/]*)/gi)[0];
    if (rootPath.startsWith('/student') && !['/studentList', '/studentCenter'].includes(rootPath)) {
      const query = getPageQuery();
      // @ts-ignore
      studentId = query.studentId || query._id;
    }
    if (!studentId) {
      return '';
    }
    return `/studentCenter?_id=${studentId}`;
  }, [props.location.pathname]);

  const authorized = getAuthorityFromRouter(props.route.routes, props.location.pathname || '/') || {
    authority: undefined,
  };

  return (
    <>
      <Helmet>
        <title>{defaultSetting.title}</title>
      </Helmet>
      <Layout>
        <Header className={styles.header}>
          <a className={styles.logo} href="/">
            <img className={styles.logoImg} src={logo} alt="" />
            <h1 className={styles.logoTitle}>{defaultSetting.title}</h1>
          </a>
          <Menu
            onClick={onMenuClick}
            theme="dark"
            mode="horizontal"
            selectedKeys={[selectKey]}
            style={{ lineHeight: '64px', flex: 1 }}
          >
            {menuList
              // @ts-ignore
              .filter(menu => menu.role.includes(props.currentUser?.role))
              .map(item => (
                <Menu.Item key={item.path}>{item.label}</Menu.Item>
              ))}
          </Menu>
          <div className={styles.avatar}>
            <Avatar />
          </div>
        </Header>
        <Content className={styles.siteLayoutContent}>
          <Authorized authority={authorized!.authority} noMatch={noMatch}>
            {props.children}
          </Authorized>
        </Content>
        <CommonFooter />
      </Layout>
    </>
  );
};

// export default PlatformLayout;
export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(PlatformLayout);
